package com.ignou.mca.subjects;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ignou.mca.beans.SubjectBean;
import com.ignou.mca.datasource.DatabaseOperations;

/**
 * Servlet implementation class Subjects
 */
public class Subjects extends HttpServlet 
{
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Subjects() 
    {
        super();
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
	{
		ServletContext context = getServletContext();
		HttpSession session = request.getSession();
		DatabaseOperations dbOperations = null;
		String CMD = request.getParameter("command");
		String subject = request.getParameter("subjectId");
		String subjectName = request.getParameter("subjectName");
		if(CMD=="update" && subject!=null)
		{
			dbOperations = new DatabaseOperations();
			int subjectID = Integer.parseInt(subject);
			SubjectBean sb = new SubjectBean();
			sb.setSubjectId(subjectID);
			sb.setSubjectName(subjectName);
			
			Boolean isUpdated = dbOperations.updateSubjectDetails(sb);
			if(isUpdated)
			{
				response.sendRedirect("./Subjects.jsp");
			}else
			{
				session.setAttribute("ErrorMessage", "Unable to to contact server at this time. <br>Please try again after sometime.");
				response.sendRedirect("./ErrorDisplay.jsp");
			}
		}else
		{
			dbOperations = new DatabaseOperations();
			SubjectBean sb = new SubjectBean();
			sb.setSubjectId(0);
			sb.setSubjectName(subjectName);
			Boolean isAdded = dbOperations.addSubjectDetails(sb);
			if(isAdded)
			{
				response.sendRedirect("./Subjects.jsp");
			}else
			{
				session.setAttribute("ErrorMessage", "Unable to to contact server at this time. <br>Please try again after sometime.");
				response.sendRedirect("./ErrorDisplay.jsp");
			}
		}
	}

}
